//
//  ALAssetRepresentation+Tools.m
//  MiaoPai
//
//  Created by jiaxuzhou on 2017/6/10.
//  Copyright © 2017年 Jeakin. All rights reserved.
//
//


#import "ALAssetRepresentation+Tools.h"
#import <objc/runtime.h>
#import <CommonCrypto/CommonCrypto.h>


#define MPT_HASH_DATA_SIZE  1024


const char * MP_AssetMD5StringKey = "MD5String";


@implementation ALAssetRepresentation (Tools)


- (NSString *)mp_MD5Lower16
{
    NSString * md5 = objc_getAssociatedObject(self, MP_AssetMD5StringKey);
    if (!md5)
    {
        CC_MD5_CTX md5ctx;
        
        CC_MD5_Init(&md5ctx);
        
        NSUInteger trunk = [self size]/MPT_HASH_DATA_SIZE;
        if ([self size] % MPT_HASH_DATA_SIZE != 0)
        {
            trunk += 1;
        }
        
        for (int i = 0; i < trunk; i++)
        {
            uint8_t buffer[MPT_HASH_DATA_SIZE];
            NSError *err = nil;
            NSUInteger dataLength = MPT_HASH_DATA_SIZE;
            if (i == (trunk - 1))
            {
                dataLength = self.size%MPT_HASH_DATA_SIZE;
            }
            
            NSUInteger gotByteCount = [self getBytes:buffer fromOffset:i * MPT_HASH_DATA_SIZE length:dataLength error:&err];
            
            if (gotByteCount)
            {
                if (err)
                {
                    NSLog(@"!!! Error reading asset: %@", [err localizedDescription]);
                }
            }
            
            CC_MD5_Update(&md5ctx, buffer, (CC_LONG)dataLength);
        }
        
        unsigned char digest[CC_MD5_DIGEST_LENGTH];
        CC_MD5_Final(digest, &md5ctx);
        NSString *md5String =  [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                                digest[0], digest[1],
                                digest[2], digest[3],
                                digest[4], digest[5],
                                digest[6], digest[7],
                                digest[8], digest[9],
                                digest[10], digest[11],
                                digest[12], digest[13],
                                digest[14], digest[15]];
        if (md5String)
        {
            md5 = md5String;
            objc_setAssociatedObject(self, MP_AssetMD5StringKey, md5, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }
    }
    
    return md5;
}


@end
